import logging
import os
import time
import pytest

from common.readData import readData
from common.Assert import Assert
from common.DButils import select,back_up,rollback
from common import loginOperater
from selenium import webdriver
from common.comDB import comDB
from common.serviceWeb import ServiceWeb
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC



com_db = comDB()
read_data=readData()

class TestRegister:
    @pytest.mark.parametrize("username,password,repassword,expect", read_data.read_data(2,4))
    def test_register(self,username,password,repassword,expect):
        # 拉起浏览器
        service = ServiceWeb()
        chromeDriver = service.get_driver("http://localhost:90/toregister.html")
        """# 登录
        login = loginOperater.LoginOperater()
        login.login(chromeDriver, username, password)
        time.sleep(1)"""

        backup=[]

        try:
            # 链接数据库
            con, cursor = com_db.get_con()
            #数据库备份
            backup = back_up("user")
            # 初始化显式等待对象
            wait = WebDriverWait(chromeDriver, 10, 0.5)

            #输入注册信息
            # 用户名输入
            username_field = wait.until(
                EC.visibility_of_element_located((By.ID, "username")),
                "用户名输入框未在10秒内可见"
            )
            username_field.clear()
            username_field.send_keys(username)
            """logging.debug(f"已输入用户名: {username}")"""

            #密码输入
            password_field = wait.until(
                EC.element_to_be_clickable((By.ID, "password")),
                "密码输入框未在10秒内可操作"
            )
            password_field.clear()
            password_field.send_keys(password)
            """logging.debug("已输入密码")"""

            # 确认密码输入
            repassword_field = wait.until(
                lambda d: d.find_element(By.ID, "repassword"),
                "确认密码输入框未在10秒内找到"
            )
            repassword_field.clear()
            repassword_field.send_keys(repassword)
            """logging.debug("已输入确认密码")"""

            #找到注册键
            regist_btn = WebDriverWait(chromeDriver,10).until(
                    EC.element_to_be_clickable((By.ID, "login_btn"))
            )
            regist_btn.click()
            time.sleep(2)
            #查询数据库
            sql1="select * from user where username=%s"
            result = len(select(sql1,(username,)))

            screenshot_dir = "D:\pythonproject\自动化_1封装\失败截图\register"
            screenshot_path = f"{screenshot_dir}/{username}失败截图.png"
            #断言
            Assert(chromeDriver,result, expect,screenshot_path)
        except Exception as e:
            con.rollback()
            raise
        finally:
            # 数据库恢复
            rollback(backup,"user")
            #资源清理
            cursor.close()
            con.close()
            chromeDriver.quit()